package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Resource
    private DeptService deptService;

    @Resource
    private EmpExprService empExprService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResult<Emp> pageResult(EmpQueryParam param) {
       Page<Emp> page=Page.of(param.getPage(), param.getPageSize());
        // 根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        /*// 构建查询条件
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());


        // 调用IService中的page方法查询分页数据
        page = page(page, queryWrapper);
*/

        // 使用LambdaQuery来构建查询条件，并返回分页结果
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);

        // 获取当前页员工集合
        List<Emp> emps = page.getRecords();

        // 获取所有员工id
        List<Integer> empIds = emps.stream().map(Emp::getDeptId).toList();

        if(!empIds.isEmpty()){
            // 批量查询这些员工的部门信息
            List<Dept> depts = deptService.listByIds(empIds);

            // 将部门名称封装到员工对象中
            emps.forEach(emp -> {
                depts.stream().filter(dept -> dept.getId().equals(emp.getDeptId()))
                        .findFirst().ifPresent(dept -> emp.setDeptName(dept.getName()));
            });
        }

        // 封装并返回结果
        return new PageResult<>(page.getTotal(), emps);
    }

    @Override
    public Emp getEmp(Integer id) {
        Emp emp = getById(id);

        // 部门名称
        emp.setDeptName(deptService.getById(emp.getDeptId()).getName());

        // 工作经历列表
        emp.setExprList(
                empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id)));
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmp(List<Integer> ids) {
        // 调用service层方法批量删除员工信息
        removeBatchByIds(ids);

        // 删除员工工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }

    @Override
    public List<Map<String,Object>> countGender() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Integer> genders= List.of(1,2);
        for (Integer gender : genders) {
            // 统计每个性别的数量
            Long count = lambdaQuery().eq(Emp::getGender, gender).count();
            // 封装结果
            Map<String, Object> map = new HashMap<>();
            map.put("name", gender==1?'男':'女');
            map.put("value", count);
            result.add(map);
        }
        return result;
    }

    @Override
    public JobCount countJob() {
        ArrayList<String> j = new ArrayList<>();
        ArrayList<Long> data = new ArrayList<>();
        Map<Integer, String> jobMap = Map.of(1, "班主任", 2, "讲师", 3, "主管", 4, "校验主管", 5, "咨询师");
        for (Integer job : jobMap.keySet()) {
            Long count = lambdaQuery().eq(Emp::getJob, job).count();
            //HashMap<String, Object> map = new HashMap<>();
           j.add(jobMap.get(job));
           data.add(count);
        }
        return new JobCount(j,data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        // 调用service层方法保存员工信息
        // 补全基础属性
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(emp.getCreateTime());

        save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        // 添加工作经历所属员工
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }

    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        //更新数据
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        // 批量保存员工的工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(exprList);
    }
}
